import React, { useEffect } from 'react';
import { Form, Input, Modal, DatePicker, InputNumber, Select } from 'antd';
import { useRequest } from '@umijs/max';
import moment from 'moment';

// 导入物资列表API
import { getMaterialList } from '@/services/materialManageApi';

interface BorrowFormProps {
  visible: boolean;
  record?: MATERIAL_BORROW.BorrowRecord;
  onCancel: () => void;
  onSubmit: (values: MATERIAL_BORROW.BorrowRecord) => void;
}

/**
 * 物资外借表单组件
 */
const BorrowForm: React.FC<BorrowFormProps> = ({ visible, record, onCancel, onSubmit }) => {
  const [form] = Form.useForm();

  // 获取物资列表
  const { data: materialList, loading: materialLoading } = useRequest(() => getMaterialList(), {
    onError: (error) => {
      console.error('获取物资列表失败:', error);
    },
  });

  // 当record变化时，更新表单数据
  useEffect(() => {
    if (visible) {
      form.resetFields();
      if (record) {
        // 编辑模式，设置表单初始值
        form.setFieldsValue({
          ...record,
          borrowTime: record.borrowTime ? moment(record.borrowTime) : undefined,
        });
      } else {
        // 新增模式，设置默认值
        form.setFieldsValue({
          borrowTime: moment(),
          borrowQuantity: 1,
        });
      }
    }
  }, [visible, record, form]);

  // 处理表单提交
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      // 转换日期格式
      const formattedValues = {
        ...values,
        borrowTime: values.borrowTime ? values.borrowTime.format('YYYY-MM-DD HH:mm:ss') : undefined,
      };
      onSubmit(formattedValues);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 当选择物资时，自动填充物资名称
  const handleMaterialChange = (value: number) => {
    if (materialList?.data) {
      const selectedMaterial = materialList.data.find((item: any) => item.id === value);
      if (selectedMaterial) {
        form.setFieldsValue({
          materialName: selectedMaterial.materialName,
        });
      }
    }
  };

  return (
    <Modal
      title={record ? '编辑物资外借记录' : '新增物资外借记录'}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={600}
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="materialId"
          label="物资"
          rules={[{ required: true, message: '请选择物资' }]}
        >
          <Select
            placeholder="请选择物资"
            loading={materialLoading}
            onChange={handleMaterialChange}
            showSearch
            optionFilterProp="children"
          >
            {materialList?.data?.map((item: any) => (
              <Select.Option key={item.id} value={item.id}>
                {item.materialName} ({item.specification})
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="materialName"
          label="物资名称"
          rules={[{ required: true, message: '请输入物资名称' }]}
        >
          <Input placeholder="请输入物资名称" disabled />
        </Form.Item>

        <Form.Item
          name="borrowerName"
          label="借用人姓名"
          rules={[{ required: true, message: '请输入借用人姓名' }]}
        >
          <Input placeholder="请输入借用人姓名" />
        </Form.Item>

        <Form.Item
          name="borrowerPhone"
          label="借用人电话"
          rules={[
            { required: true, message: '请输入借用人电话' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
          ]}
        >
          <Input placeholder="请输入借用人电话" />
        </Form.Item>

        <Form.Item
          name="borrowerClass"
          label="借用人班级"
          rules={[{ required: true, message: '请输入借用人班级' }]}
        >
          <Input placeholder="请输入借用人班级" />
        </Form.Item>

        <Form.Item
          name="purpose"
          label="用途"
          rules={[{ required: true, message: '请输入用途' }]}
        >
          <Input placeholder="请输入用途" />
        </Form.Item>

        <Form.Item
          name="borrowQuantity"
          label="借用数量"
          rules={[
            { required: true, message: '请输入借用数量' },
            { type: 'number', min: 1, message: '借用数量必须大于0' },
          ]}
        >
          <InputNumber placeholder="请输入借用数量" min={1} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="borrowTime"
          label="借用时间"
          rules={[{ required: true, message: '请选择借用时间' }]}
        >
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择借用时间"
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item name="remark" label="备注">
          <Input.TextArea rows={4} placeholder="请输入备注信息" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default BorrowForm;